<template>
    <div class="spelling-screen" :style="{ backgroundImage: `url(${bgUrl})` }">
        <div class="blur-overlay"></div>
        
        <header class="topbar">
            <div class="top-left">
                <div class="progress">{{ currentIndex + 1 }}/{{ totalWords }}</div>
            </div>
            <div class="top-right">
                <button class="icon-btn" aria-label="star" @click="noop">★</button>
            </div>
        </header>
        
        <main class="spelling-content">
            <!-- 输入区域 -->
            <div class="input-section">
                <div class="input-label">请输入单词</div>
                <div class="input-wrapper" :class="{ correct: isCorrect, wrong: isWrong }">
                    <input 
                        type="text" 
                        v-model="inputWord" 
                        @keyup.enter="checkSpelling"
                        @keydown.space="handleSpaceKey"
                        @input="handleInput"
                        :disabled="isChecking || isCorrect"
                        class="word-input"
                        :class="{ correct: isCorrect, wrong: isWrong }"
                        placeholder="输入英文拼写"
                        ref="inputRef"
                        autocomplete="off"
                        spellcheck="false"
                    />
                    <div class="input-underline"></div>
                    <transition name="zoom-pop">
                        <div 
                            class="status-indicator" 
                            v-if="isCorrect || isWrong" 
                            :class="{ correct: isCorrect, wrong: isWrong }"
                        >
                            {{ isCorrect ? '✔' : '✘' }}
                        </div>
                    </transition>
                </div>
            </div>

            <!-- 单词意思显示 -->
            <transition name="fade-up" mode="out-in">
                <div class="meaning-section" v-if="currentWord.wordId">
                    <div class="part-of-speech" v-if="currentWord.partOfSpeech">{{ currentWord.partOfSpeech }}</div>
                    <div class="meaning-text">{{ currentWord.correctMeaning || currentWord.meaning }}</div>
                </div>
                <div class="loading-state" v-else-if="isLoading">正在加载单词...</div>
                <div class="empty-state" v-else>暂无单词数据</div>
            </transition>
            
            <!-- 结果显示 -->
            <transition name="fade-up">
                <div class="result-section" v-if="isCorrect || isWrong">
                    <div class="result-text" :class="{ correct: isCorrect, wrong: isWrong }">
                        {{ isCorrect ? '正确！' : '错误！' }}
                    </div>
                    <div class="correct-word" v-if="isWrong">
                        正确答案: {{ currentWord.word }}
                    </div>
                </div>
            </transition>
            
            <!-- 提示 -->
            <transition name="fade-up">
                <div class="hint-text" v-if="!isCorrect && !isWrong">
                    输入完成后按回车键开始校验
                </div>
            </transition>
        </main>
        
        <!-- 底部关闭按钮 -->
        <footer class="spelling-footer">
            <button class="close-btn" @click="showExitConfirm">
                <svg viewBox="0 0 24 24" width="24" height="24">
                    <path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
                </svg>
            </button>
        </footer>
        
        <!-- 退出确认弹窗 -->
        <div class="exit-modal" v-if="showExitModal" @click.self="hideExitConfirm">
            <div class="modal-content">
                <div class="modal-title">确定放弃拼写测试吗?</div>
                <div class="modal-message">放弃后将无法继续拼写本组单词</div>
                <div class="modal-buttons">
                    <button class="modal-btn cancel-btn" @click="hideExitConfirm">取消</button>
                    <button class="modal-btn confirm-btn" @click="exitSpelling">放弃</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { bgUrl } from '@/config/background.js'
import { fetchSpellingWords } from '@/utils/api.js'

const router = useRouter()
const route = useRoute()

// 从路由参数获取数据
const mode = ref(route.query.mode || 'learn')
const wordIds = ref(route.query.wordIds ? route.query.wordIds.split(',').map(id => parseInt(id)) : [])
const sessionId = ref(route.query.sessionId || '')

// 数据状态
const wordList = ref([])
const currentIndex = ref(0)
const inputWord = ref('')
const isChecking = ref(false)
const isCorrect = ref(false)
const isWrong = ref(false)
const showExitModal = ref(false)
const inputRef = ref(null)
const isLoading = ref(false)
const previousInput = ref('') // 记录之前的输入，用于检测是否继续输入

// 计算属性
const totalWords = computed(() => wordList.value.length)
const currentWord = computed(() => wordList.value[currentIndex.value] || {})

// 获取拼写单词列表
async function loadSpellingWords() {
    try {
        isLoading.value = true
        // 首先尝试从sessionStorage获取（刚刚学习/复习过的单词）
        loadWordsFromSession()
        
        // 如果sessionStorage没有数据，再尝试从API获取
        if (wordList.value.length === 0) {
            const words = await fetchSpellingWords(wordIds.value, mode.value)
            if (words && words.length > 0) {
                wordList.value = words
            }
        }
    } catch (error) {
        console.error('获取拼写单词失败:', error)
        // API失败时，尝试从sessionStorage获取
        if (wordList.value.length === 0) {
            loadWordsFromSession()
        }
    } finally {
        isLoading.value = false
    }
    
    if (wordList.value.length > 0) {
        // 聚焦输入框
        nextTick(() => {
            if (inputRef.value) {
                inputRef.value.focus()
            }
        })
    }
}

// 从sessionStorage加载单词数据
function loadWordsFromSession() {
    try {
        if (sessionId.value) {
            const sessionDataStr = sessionStorage.getItem(`study_session_${sessionId.value}`)
            if (sessionDataStr) {
                const sessionData = JSON.parse(sessionDataStr)
                // 使用保存的单词列表，提取拼写所需的信息
                wordList.value = sessionData.wordList.map(word => ({
                    wordId: word.wordId,
                    word: word.word,
                    partOfSpeech: word.partOfSpeech,
                    correctMeaning: word.correctMeaning,
                    meaning: word.correctMeaning, // 兼容字段
                    phonetic: word.phonetic
                }))
            }
        }
    } catch (error) {
        console.error('从sessionStorage加载单词失败:', error)
    }
}

// 处理输入
function handleInput(event) {
    const currentValue = event.target.value
    
    // 如果之前输入错误，用户继续输入时，先清除输入框，再显示新输入的字母
    if (isWrong.value && previousInput.value !== currentValue) {
        // 检测是否是继续输入（输入框的值发生了变化）
        // 如果当前值比之前的值长，说明用户在继续输入，需要清除之前的输入，只保留新输入
        if (currentValue.length > previousInput.value.length) {
            // 获取新输入的字符（当前值中不在之前值中的部分）
            const newChars = currentValue.slice(previousInput.value.length)
            // 清除输入框，只保留新输入的字符
            inputWord.value = newChars
            // 清除错误状态
            isWrong.value = false
            isCorrect.value = false
            // 更新 previousInput 为新输入
            previousInput.value = newChars
            return // 提前返回，避免再次更新 previousInput
        } else {
            // 如果当前值比之前的值短或相同，说明用户删除了部分内容或没有变化
            // 只清除错误状态
            isWrong.value = false
            isCorrect.value = false
        }
    } else {
        // 清除之前的结果（如果之前是正确的）
        if (isCorrect.value) {
            isCorrect.value = false
            isWrong.value = false
        }
    }
    
    // 更新 previousInput
    previousInput.value = currentValue
}

// 处理空格键：当输入框为空时，按空格表示"不认识"，直接显示正确答案
function handleSpaceKey(event) {
    // 如果输入框为空或只有空格，且没有输入任何字母
    if (!inputWord.value.trim() && !isChecking.value && !isCorrect.value) {
        event.preventDefault() // 阻止默认的空格输入
        // 直接显示正确答案
        showCorrectAnswer()
    }
}

// 显示正确答案（不认识的情况）
function showCorrectAnswer() {
    isWrong.value = true
    isCorrect.value = false
    // 显示正确答案，但不自动进入下一题，等待用户继续操作
}

// 校验拼写
function checkSpelling() {
    if (isChecking.value || isCorrect.value || !inputWord.value.trim()) return
    
    isChecking.value = true
    const userInput = inputWord.value.trim().toLowerCase()
    const correctWord = (currentWord.value.word || '').toLowerCase()
    
    // 更新 previousInput，记录校验时的输入
    previousInput.value = inputWord.value
    
    // 简单的校验（可以后续优化，比如忽略大小写、空格等）
    if (userInput === correctWord) {
        isCorrect.value = true
        isWrong.value = false
        // 1.5秒后自动进入下一题
        setTimeout(() => {
            if (currentIndex.value < wordList.value.length - 1) {
                nextWord()
            } else {
                // 拼写完成，返回首页
                router.push('/')
            }
        }, 1500)
    } else {
        isCorrect.value = false
        isWrong.value = true
        // 显示正确答案后，用户可以继续输入或按回车重新校验
    }
    
    isChecking.value = false
}

// 下一题
function nextWord() {
    if (currentIndex.value < wordList.value.length - 1) {
        currentIndex.value++
        inputWord.value = ''
        previousInput.value = '' // 重置之前的输入记录
        isCorrect.value = false
        isWrong.value = false
        // 聚焦输入框
        nextTick(() => {
            if (inputRef.value) {
                inputRef.value.focus()
            }
        })
    } else {
        // 拼写完成，返回首页
        router.push('/')
    }
}

// 显示退出确认
function showExitConfirm() {
    showExitModal.value = true
}

// 隐藏退出确认
function hideExitConfirm() {
    showExitModal.value = false
}

// 退出拼写
function exitSpelling() {
    hideExitConfirm()
    router.push('/')
}

function noop() {}

onMounted(() => {
    loadSpellingWords()
})

onBeforeUnmount(() => {
    // 清理
})
</script>

<style scoped>
.spelling-screen {
    position: fixed;
    inset: 0;
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
    color: #ffffff;
    display: flex;
    flex-direction: column;
}

.blur-overlay {
    position: absolute;
    inset: 0;
    backdrop-filter: blur(35px) brightness(0.95) saturate(1.05);
    -webkit-backdrop-filter: blur(35px) brightness(0.95) saturate(1.05);
    background: rgba(25, 35, 40, 0.25);
    z-index: 0;
}

.topbar {
    position: relative;
    z-index: 1;
    height: 56px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
}

.top-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.progress {
    color: #cbd5e1;
    font-weight: 600;
    font-size: 15px;
}

.top-right {
    display: flex;
    align-items: center;
}

.icon-btn {
    border: none;
    background: transparent;
    cursor: pointer;
    color: #e2e8f0;
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.spelling-content {
    position: relative;
    z-index: 1;
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 48px 24px;
    gap: 32px;
}

.meaning-section {
    text-align: center;
    max-width: 600px;
    width: 100%;
}

.part-of-speech {
    font-size: 18px;
    color: #94a3b8;
    margin-bottom: 12px;
    font-weight: 500;
}

.meaning-text {
    font-size: 24px;
    color: #ffffff;
    line-height: 1.6;
    font-weight: 500;
    text-shadow: 0 8px 30px rgba(15, 23, 42, 0.4);
}

.input-section {
    width: 100%;
    max-width: 460px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
}

.input-label {
    font-size: 14px;
    letter-spacing: 0.32em;
    text-transform: uppercase;
    color: rgba(226, 232, 240, 0.8);
}

.input-wrapper {
    width: 100%;
    position: relative;
    padding: 26px 32px 24px;
    border-radius: 24px;
    background: rgba(15, 23, 42, 0.45);
    box-shadow: 0 24px 60px rgba(15, 23, 42, 0.45);
    backdrop-filter: blur(18px);
    -webkit-backdrop-filter: blur(18px);
    transition: all 0.35s ease;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 18px;
}

.input-wrapper.correct {
    background: rgba(16, 185, 129, 0.14);
    box-shadow: 0 24px 60px rgba(16, 185, 129, 0.32);
}

.input-wrapper.wrong {
    background: rgba(239, 68, 68, 0.14);
    box-shadow: 0 24px 60px rgba(239, 68, 68, 0.32);
}

.input-wrapper:focus-within {
    transform: translateY(-3px);
    box-shadow: 0 26px 65px rgba(248, 250, 252, 0.18);
}

.word-input {
    width: 100%;
    background: transparent;
    border: none;
    border-bottom: 2px solid rgba(255, 255, 255, 0.3);
    color: #ffffff;
    font-size: 32px;
    font-weight: 600;
    text-align: center;
    padding: 12px 0;
    outline: none;
    transition: all 0.35s ease;
    letter-spacing: 2px;
}

.word-input:focus {
    border-bottom-color: #fbbf24;
}

.word-input.correct {
    border-bottom-color: #10b981;
    color: #10b981;
    animation: correctPulse 0.55s ease forwards;
}

.word-input.wrong {
    border-bottom-color: #ef4444;
    color: #ef4444;
    animation: shake 0.4s ease;
}

.word-input:disabled {
    opacity: 0.7;
    cursor: not-allowed;
}

.input-underline {
    position: absolute;
    bottom: 12px;
    left: 32px;
    right: 32px;
    height: 3px;
    background: linear-gradient(90deg, rgba(248, 250, 252, 0.08) 0%, rgba(248, 250, 252, 0.2) 100%);
    transform: scaleX(0);
    transform-origin: center;
    border-radius: 999px;
    transition: transform 0.35s ease, background 0.35s ease;
}

.input-wrapper:focus-within .input-underline {
    transform: scaleX(1);
    background: linear-gradient(90deg, rgba(248, 250, 252, 0.2) 0%, rgba(248, 250, 252, 0.3) 100%);
}

.input-wrapper.correct .input-underline {
    transform: scaleX(1);
    background: linear-gradient(90deg, #22c55e 0%, #0ea5e9 100%);
}

.input-wrapper.wrong .input-underline {
    transform: scaleX(1);
    background: linear-gradient(90deg, #f87171 0%, #fb7185 100%);
}

.status-indicator {
    position: absolute;
    top: -18px;
    right: -18px;
    width: 48px;
    height: 48px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    font-weight: 700;
    color: #0f172a;
    backdrop-filter: blur(16px);
    -webkit-backdrop-filter: blur(16px);
    box-shadow: 0 12px 24px rgba(15, 23, 42, 0.18);
}

.status-indicator.correct {
    background: rgba(16, 185, 129, 0.85);
    color: #064e3b;
}

.status-indicator.wrong {
    background: rgba(248, 113, 113, 0.85);
    color: #7f1d1d;
}

.result-section {
    text-align: center;
    min-height: 60px;
}

.result-text {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 8px;
}

.result-text.correct {
    color: #10b981;
}

.result-text.wrong {
    color: #ef4444;
}

.correct-word {
    font-size: 16px;
    color: #94a3b8;
}

.hint-text {
    font-size: 14px;
    color: #94a3b8;
    text-align: center;
}

.loading-state,
.empty-state {
    font-size: 16px;
    color: rgba(226, 232, 240, 0.7);
    letter-spacing: 1px;
}

.empty-state {
    color: rgba(226, 232, 240, 0.5);
}

.fade-up-enter-active,
.fade-up-leave-active {
    transition: all 0.35s ease;
}

.fade-up-enter-from,
.fade-up-leave-to {
    opacity: 0;
    transform: translateY(12px);
}

.zoom-pop-enter-active,
.zoom-pop-leave-active {
    transition: all 0.25s ease;
}

.zoom-pop-enter-from,
.zoom-pop-leave-to {
    opacity: 0;
    transform: scale(0.6) translateY(-6px);
}

.zoom-pop-enter-to,
.zoom-pop-leave-from {
    opacity: 1;
    transform: scale(1) translateY(0);
}

@keyframes correctPulse {
    0% {
        transform: scale(1);
        box-shadow: 0 0 0 rgba(16, 185, 129, 0.0);
    }
    40% {
        transform: scale(1.03);
        box-shadow: 0 14px 40px rgba(16, 185, 129, 0.45);
    }
    100% {
        transform: scale(1);
        box-shadow: 0 8px 24px rgba(16, 185, 129, 0.25);
    }
}

@keyframes shake {
    0%,
    100% {
        transform: translateX(0);
    }
    20%,
    60% {
        transform: translateX(-10px);
    }
    40%,
    80% {
        transform: translateX(10px);
    }
}

.spelling-footer {
    position: relative;
    z-index: 1;
    padding: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.close-btn {
    width: 48px;
    height: 48px;
    border: none;
    background: rgba(255, 255, 255, 0.1);
    color: #ffffff;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    backdrop-filter: blur(8px);
}

.close-btn:hover {
    background: rgba(255, 255, 255, 0.2);
    transform: rotate(90deg);
}

/* 退出确认弹窗 */
.exit-modal {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    padding: 20px;
}

.modal-content {
    background: rgba(30, 41, 59, 0.95);
    border-radius: 16px;
    padding: 24px;
    max-width: 360px;
    width: auto;
    min-width: 280px;
    backdrop-filter: blur(20px);
}

.modal-title {
    font-size: 18px;
    font-weight: 600;
    color: #ffffff;
    margin-bottom: 16px;
    text-align: center;
    letter-spacing: 0.3px;
}

.modal-message {
    font-size: 14px;
    color: #94a3b8;
    margin-bottom: 32px;
    text-align: center;
    line-height: 1.8;
    letter-spacing: 0.2px;
}

.modal-buttons {
    display: flex;
    gap: 16px;
    justify-content: center;
}

.modal-btn {
    padding: 12px 32px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
    letter-spacing: 0.5px;
}

.cancel-btn {
    background: rgba(255, 255, 255, 0.1);
    color: #ffffff;
}

.cancel-btn:hover {
    background: rgba(255, 255, 255, 0.15);
}

.confirm-btn {
    background: #ef4444;
    color: #ffffff;
}

.confirm-btn:hover {
    background: #dc2626;
}
</style>

